import axios from "axios";
import fs from 'fs';

axios.defaults.maxRedirects = 0;

const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46';

const validateStatus = (status: number) => {
    return status >= 200 && status <= 303; // 默认的范围是 200-299，这里我们把302也视为正常
}

const addComment = (photoId: string, photoAuthorId: string, cookieStr: string, content: string, expTag: string) => {
    const url = 'https://www.kuaishou.com/graphql';

    const headers = {
        "User-Agent": userAgent,
        Cookie: cookieStr
    };

    const data = {
        operationName: "visionAddComment",
        variables: {
            photoId,
            photoAuthorId,
            content,
            expTag
        },
        "query": "mutation visionAddComment($photoId: String, $photoAuthorId: String, $content: String, $replyToCommentId: ID, $replyTo: ID, $expTag: String) {\n  visionAddComment(photoId: $photoId, photoAuthorId: $photoAuthorId, content: $content, replyToCommentId: $replyToCommentId, replyTo: $replyTo, expTag: $expTag) {\n    result\n    commentId\n    content\n    timestamp\n    status\n    __typename\n  }\n}\n"
    };

    return axios.post(url, data, { headers });
}

const getOwnerInfo = async (photoId: string, cookieStr: string) => {
    const url = `https://www.kuaishou.com/short-video/${photoId}`;

    const headers = {
        "User-Agent": userAgent,
        Cookie: cookieStr
    };

    const res = await axios.get(url, { headers });
    const str = res.data;
    let regex = /"expTag":"([^"]*)"/; // 正则表达式匹配 "expTag":"任意字符，直到遇到另一个双引号"
    let match = regex.exec(str); // 执行匹配操作
    let expTag ='';
    if (match?.length) {
        expTag = match[1];
    }
    let photoAuthorId ='';
    regex = /"VisionVideoDetailAuthor:([^"]*)"/; // 正则表达式匹配 "expTag":"任意字符，直到遇到另一个双引号"
    match = regex.exec(str); // 执行匹配操作
    if (match?.length) {
        photoAuthorId = match[1];
    }

    return {
        expTag: expTag.replace('\\u002F', '/'),
        photoAuthorId
    };
}

const main = async (userId: string) => {
    const passToken = fs.readFileSync(`./userData/${userId}`, 'utf-8');
    

    const time = Date.now();
    const url = `https://id.kuaishou.com/pass/kuaishou/login/passToken?callback=https%3A%2F%2Fwww.kuaishou.com%2Frest%2Finfra%2Fsts%3FfollowUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dtrue%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26failUrl%3Dhttps%253A%252F%252Fpassport.kuaishou.com%252Fpc%252Faccount%252FpassToken%252Fresult%253Fsuccessful%253Dfalse%2526id%253DSSO_${time}%2526for%253DpassTokenSuccess%26setRootDomain%3Dfalse&__loginPage=https%3A%2F%2Fpassport.kuaishou.com%2Fpc%2Faccount%2FpassToken%2Fresult%3Fsuccessful%3Dfalse%26id%3DSSO_${time}%26for%3DpullTokenFail&sid=kuaishou.server.web`
    const Cookie = `userId=${userId}; passToken=${passToken}`;
    const headers = {
        "User-Agent": userAgent,
        Cookie
    };
    const res = await axios.get(url, { headers, validateStatus });
    const res2 = await axios.get(res.headers.location, { headers, validateStatus });
    const cookies = res2.headers['set-cookie'] || [];
    const cookieStr = cookies.map(item => item.split(';')[0]).join('; ');
    console.log(cookieStr)
    // this._cookieStr = cookieStr;
    const photoId = '3xcsvwg5xx4apwq';
    const ownerInfo = await getOwnerInfo(photoId, cookieStr);
    const addRes = await addComment(photoId, ownerInfo.photoAuthorId, cookieStr, "您好", ownerInfo.expTag);
    if (addRes.data.data && addRes.data.data.visionAddComment && addRes.data.data.visionAddComment.status === 'success') {
        console.log('评论成功');
    } else {
        console.log(addRes.data);
    }
    
};

main('865484597');
























// 